package com.chatplus.application.controller.admin.file;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.page.PageParam;
import com.chatplus.application.domain.entity.file.SysOssEntity;
import com.chatplus.application.domain.request.PlusPageRequest;
import com.chatplus.application.domain.response.PlusPageResponse;
import com.chatplus.application.domain.response.admin.SysOssResponse;
import com.chatplus.application.service.file.SysOssService;
import com.chatplus.application.web.basecontroller.BaseController;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传 控制层
 */
@Validated
@RestController
@RequestMapping("/api/admin/oss")
public class SysOssController extends BaseController {

    private final SysOssService iSysOssService;

    public SysOssController(SysOssService iSysOssService) {
        this.iSysOssService = iSysOssService;
    }

    @PostMapping("/list")
    @Operation(summary = "后台获取文件分页列表")
    public PlusPageResponse<SysOssResponse> list(@RequestBody PlusPageRequest plusPageRequest) {
        PageParam pageParam = new PageParam(plusPageRequest.getPage(), plusPageRequest.getPageSize());
        LambdaQueryWrapper<SysOssEntity> queryWrapper = Wrappers.<SysOssEntity>lambdaQuery()
                .orderByDesc(SysOssEntity::getCreatedAt);
        Page<SysOssEntity> pageDTO = iSysOssService.page(pageParam.toPage(), queryWrapper);
        List<SysOssEntity> orderEntityList = pageDTO.getRecords();
        if (CollUtil.isEmpty(orderEntityList)) {
            return new PlusPageResponse<>(plusPageRequest.getPage(), plusPageRequest.getPageSize(), 0, 0, Lists.newArrayList());
        }
        List<SysOssResponse> responseList = orderEntityList.stream().map(SysOssResponse::build).toList();
        return new PlusPageResponse<>(pageParam.getCurrent(), pageParam.getSize()
                , pageDTO.getPages(), pageDTO.getTotal(), responseList);
    }

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Map<String, String> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new BadRequestException("上传文件不能为空");
        }
        SysOssEntity oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>();
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getId().toString());
        return map;
    }

    /**
     * 下载OSS对象
     *
     * @param ossId OSS对象ID
     */
    @GetMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        iSysOssService.download(ossId, response);
    }

    /**
     * 删除OSS对象存储
     *
     * @param ossIds OSS对象ID串
     */
    @DeleteMapping("/{ossIds}")
    public void remove(@NotEmpty(message = "主键不能为空")
                       @PathVariable Long[] ossIds) {
        iSysOssService.deleteByIds(Arrays.asList(ossIds));
    }

}
